package smartq.app;

import java.sql.ResultSet;

import smartq.DB.BookQ;
import smartq.DB.Connect;
import smartq.DB.Table;
import smartq.general.DateTime;

import com.app.smart_q.R;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SmartQ_Manage_Activity extends Activity {

	// Counter of time since app started ,a background task

	// Handler to handle the message to the timer task
	private Handler mHandler = new Handler();

	static final int UPDATE_INTERVAL = 1000;

	String timerStop1;

	Connect con = new Connect();
	ResultSet rs;
	String OID, UsrOpt, IsActive, IsDeleted, CustomerPhonenumber,
			CustomerFirstName, CustomerLastName, CustomerSex, CustomerClass,
			CustomerShop, CustomerFood, CustomerTime = "-", CustomerAlet,
			CustomerTable, CustomerNumber, CustomerStartTime, CustomerEndTime,
			CustomerQ, CustomerStatus, CustomerIsMessage, CustomerWaittime;

	private TextView etTimeCustomer, etTimeNow, etTimewait;
	private Button btShowlist, btCancle;
	public boolean ckAlert = false;
	public String TimeAlert;

	// -------GET_SET-----------------------------------//

	
	public String getOID() {
		return OID;
	}

	public String getTimeAlert() {
		return TimeAlert;
	}

	public void setTimeAlert(String min) {
		TimeAlert = min;
	}

	public void setOID(String oID) {
		OID = oID;
	}

	DateTime dt = new DateTime();
	CountDownTimer timer1;
	String tag;

	@SuppressWarnings("static-access")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.smartq_manage);

		etTimeCustomer = (TextView) findViewById(R.id.editText_TimeCustomer);
		etTimeNow = (TextView) findViewById(R.id.editText_TimeNow);
		etTimewait = (TextView) findViewById(R.id.editText_Timewait);

		btShowlist = (Button) findViewById(R.id.smartqmain_showq);
		btCancle = (Button) findViewById(R.id.smartq_cancle);

		// Log.d(tag, "In the OnCreate() event");

	}

	@SuppressWarnings("deprecation")
	public void Alert() {
		// ---แจ้งเตือน-------
		final NotificationManager notiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		final Notification noti = new Notification(R.drawable.ic_launcher,
				"Notification Text", System.currentTimeMillis());
		Intent intent = getBaseContext().getPackageManager()
				.getLaunchIntentForPackage(getBaseContext().getPackageName());
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent destIntent = PendingIntent
				.getActivity(this, 0, intent, 0);

		noti.setLatestEventInfo(this, "SmartQ", "อีก " +getTimeAlert()+ " นาทีจะถึงคิวของคุณ",
				destIntent);

		noti.defaults |= Notification.DEFAULT_SOUND;
		noti.defaults |= Notification.DEFAULT_VIBRATE;
		notiManager.notify(3, noti);

	}

	//
	// public void onStart(){
	// super.onStart();
	// Log.d(tag, "In the onStart() event");
	// }

	@SuppressWarnings("static-access")
	public void onResume() {

		super.onResume();
		CustomerTime = "-";
		Bundle bundle = getIntent().getExtras();
		CustomerPhonenumber = (String) bundle.get("CustomerPhonenumber");

		BookQ usr = new BookQ();
		final DateTime dt = new DateTime();
		String DateNow = dt.getDateNowymd();

		try {
			rs = usr.selectBookQ(CustomerPhonenumber, "1", DateNow, "",
					"Waiting");
			if (rs.next()) {
				btCancle.setEnabled(true);
				setOID(rs.getString("OID"));
				CustomerFirstName = rs.getString("CustomerFirstName");
				CustomerLastName = rs.getString("CustomerLastName");
				CustomerSex = rs.getString("CustomerSex");
				CustomerClass = rs.getString("CustomerClass");
				CustomerShop = rs.getString("CustomerShop");
				CustomerFood = rs.getString("CustomerFood");
				CustomerTime = rs.getString("CustomerTime");
				CustomerAlet = rs.getString("CustomerAlet");
				CustomerTable = rs.getString("CustomerTable");
				CustomerNumber = rs.getString("CustomerNumber");
				CustomerIsMessage = rs.getString("CustomerIsMessage");
				etTimeCustomer.setText(CustomerTime+":00");
				
				String tnn = dt.getTimeNow();
				String tuu = CustomerTime;
				int TNN=dt.convertTime(tnn);
				int TUU=dt.convertTime(tuu);
				for(int i=5;i<=60;i+=5){
					if(CustomerIsMessage.equals("ล่วงหน้า "+i+" นาที")){
						setTimeAlert(String.valueOf(i));
						break;
					}
				}
				
			} else {
				btCancle.setEnabled(false);
				etTimeCustomer.setText("-");
				CustomerTime = "-";
			}
		} catch (Exception e) {
			finish();
		}
//		String tnn = dt.getTimeNow();
//		int Tm = dt.convertTime(tnn);
//		int Tc = dt.convertTime(CustomerTime);
//		long Tr = Math.abs(Tc - Tm);
		
	//	timer1 = new CountDownTimer(Tr * 60 * 1000,1000);
//		timer1 = new CountDownTimer(Tr * 60 * 1000, 1000) {
//
//			@Override
//			public void onFinish() {
//
//				etTimewait.setText("-");
//			}
//
//			@Override
//			public void onTick(long millisUntilFinished) {
//
////				int seconds = (int) (millisUntilFinished / 1000);
////				int minutes = seconds / 60;
////				int hr = minutes / 60;
////				minutes = minutes % 60;
//
//
////				etTimewait.setText("" + String.format("%02d", hr) + ":"
////						+ String.format("%02d", minutes));
////				etTimewait.setTextColor(Color.RED);
//				
//				String TC = etTimeCustomer.getText().toString();
//				String TN = etTimeNow.getText().toString();
//				int tcc = dt.convertTimess(TC);
//				int tnn = dt.convertTimess(TN);
//				
//				if((tcc-tnn)>0){
//					int a= tcc-tnn;
//					int HH = a/360;
//					int mm = HH/60;
//					int ss = HH%60;
//					String HH1="-",mm1="-",ss1="-";
//					if (Math.abs(mm - TimeAlert) <= 1  && HH == 0
//							&& ckAlert == false) {
//						Alert();
//						ckAlert = true;
//					}
//					
//					if(HH<10){
//						HH1="0"+String.valueOf(HH);
//					}
//					if(mm<10){
//						mm1="0"+String.valueOf(mm);
//					}
//					if(ss<10){
//						ss1="0"+String.valueOf(ss);
//					}
//					
//					etTimewait.setText(HH1+":"+mm1+":"+ss1);
//				}
//
//			}
//		};
//		
//		if (!etTimeCustomer.getText().toString().equals("-")) {
//			timer1.start();
//		}else{
//			timer1.cancel();
//		}

		

		// Watch for button clicks.
		btShowlist.setOnClickListener(buttonShowList);
		btCancle.setOnClickListener(buttonCancle);

		etTimeNow.setText("-");
		etTimewait.setText("-");

		mHandler.removeCallbacks(mUpdateTimeTask);
		mHandler.postDelayed(mUpdateTimeTask, 100);

		// etTimewait.setText(String.valueOf(Tr));

		// Log.d(tag, "In the onResume() event");
	}
	


	// public void onStop(){
	// super.onStop();
	// Log.d(tag, "In the onStop() event");
	// }

	public void onPause() {
		super.onPause();
		// Log.d(tag, "In the onPause() event");
		//timer1.cancel();
	}

	//
	// public void onRestart(){
	// super.onRestart();
	// Log.d(tag, "In the onRestart() event");
	// }
	//
	// public void onDestroy(){
	// super.onDestroy();
	// Log.d(tag, "In the onDestroy() event");
	// }
	//
	private Runnable mUpdateTimeTask = new Runnable() {

		@SuppressWarnings("static-access")
		public void run() {
			
			
			String Timenow = dt.getTimeNowss();

			etTimeNow.setText(Timenow);
			etTimeNow.setTextColor(Color.BLUE);
			mHandler.postDelayed(this, 100);
			
			String TC = etTimeCustomer.getText().toString();
			String TN = etTimeNow.getText().toString();
			if(!TC.equals("-")){
				int tcc = dt.convertTimess(TC);
				int tnn = dt.convertTimess(TN);
				
				if((tcc-tnn)>0){
					int a= tcc-tnn;
					int HH = a/3600;
					int mm = (a%3600)/60;
					int ss = (a%3600)%60;
					String HH1="-",mm1="-",ss1="-";
					
					if (mm <= (Integer.valueOf(getTimeAlert()))   && HH == 0
							&& ckAlert == false) {
						setTimeAlert(String.valueOf(mm));
						Alert();
						ckAlert = true;
					}
					
					if(HH<10){
						HH1="0"+String.valueOf(HH);
					}else{
						HH1=String.valueOf(HH);
					}
					if(mm<10){
						mm1="0"+String.valueOf(mm);
					}else{
						mm1=String.valueOf(mm);
					}
					if(ss<10){
						ss1="0"+String.valueOf(ss);
					}else{
						ss1=String.valueOf(ss);
					}
					
					etTimewait.setText(HH1+":"+mm1+":"+ss1);
					//etTimewait.setText(a+":"+HH+":"+mm+"/"+ss);
					etTimewait.setTextColor(Color.RED);
					//etTimewait.setText(String.valueOf(tcc-tnn));
				}
			}else{
				etTimewait.setText("-");
			}
			
			

		}
	};
	private OnClickListener buttonShowList = new OnClickListener() {
		public void onClick(View v) {
			Intent newActivity = new Intent(SmartQ_Manage_Activity.this,
					SmartQ_ListShowQ.class);
			newActivity.putExtra("CustomerPhonenumber", CustomerPhonenumber);
			startActivity(newActivity);
			finish();
		}
	};

	private OnClickListener buttonCancle = new OnClickListener() {
		public void onClick(View v) {
			onCancle();
		}
	};

	public void onCancle() {

		new AlertDialog.Builder(this)
				.setTitle("ยกเลิกคิว")
				.setMessage("ทำการยกเลิกคิว")
				.setNegativeButton(android.R.string.yes,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
								BookQ usr = new BookQ(getOID(), "NFC", "1",
										null, null, null, null, null, null,
										null, null, null, null, null, null,
										null, null, null, "Cancle", null, null);
								try {
									if (usr.OperationData("UpdateStatus") != null) {
										final DateTime dt = new DateTime();
										@SuppressWarnings("static-access")
										String DateNow = dt.getDateNowymd();
										BookQ usr2 = new BookQ();
										rs = usr2.selectBookQ("", "1", getOID(), "",
												"");
										if(rs.next()){
											ResultSet rs2=null;
											Table usr3 = new Table();
											rs2 = usr3.selectTable(rs.getString("CustomerTable"));
											if(rs2.next()){
												String OID = rs2.getString("OID");
												Table usr4 = new Table(
														OID,
														CustomerPhonenumber, 
														"1", 
														null, 
														
														null,
														"Free",
														null,
														"-"
														);
											if (usr4.OperationData("Update") != null) {
												Intent newActivity = new Intent(
														getApplicationContext(),
														SmartQ_Tap_Main.class);
												newActivity.putExtra(
														"CustomerPhonenumber",
														CustomerPhonenumber);
												startActivity(newActivity);
												finish();
											}
											}
											
										}
										
									}
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}).setPositiveButton(android.R.string.no, null)
				.create().show();

	}

	@Override
	public void onBackPressed() {

		new AlertDialog.Builder(this)
				.setTitle("ออกจากโปรแกรม")
				.setMessage("ต้องการออกจากโปรแกรม")
				.setNegativeButton(android.R.string.yes,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
								finish();
								System.exit(0);
							}
						}).setPositiveButton(android.R.string.no, null)
				.create().show();

	}

}
